package cn.iocoder.yudao.module.system.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 报告生成性能优化配置
 *
 * @author zhaoying
 */
@Slf4j
@Configuration
@EnableAsync
public class ReportPerformanceConfig {

    /**
     * 报告生成专用线程池
     * 用于异步处理报告生成任务，避免阻塞主线程
     */
    @Bean("reportGenerateExecutor")
    public Executor reportGenerateExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数：CPU核心数的2倍
        int corePoolSize = Math.max(8, Runtime.getRuntime().availableProcessors() * 2);
        executor.setCorePoolSize(corePoolSize);
        
        // 最大线程数：CPU核心数的4倍
        int maxPoolSize = Math.max(16, Runtime.getRuntime().availableProcessors() * 4);
        executor.setMaxPoolSize(maxPoolSize);
        
        // 队列容量：设置为较大值，避免任务被拒绝
        executor.setQueueCapacity(1000);
        
        // 线程空闲时间：60秒
        executor.setKeepAliveSeconds(60);
        
        // 线程名前缀
        executor.setThreadNamePrefix("ReportGenerate-");
        
        // 拒绝策略：调用者运行策略，避免任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 等待所有任务完成后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 等待时间：30秒
        executor.setAwaitTerminationSeconds(30);
        
        executor.initialize();
        
        log.info("[ReportPerformanceConfig][报告生成线程池初始化完成] corePoolSize={}, maxPoolSize={}, queueCapacity={}",
                corePoolSize, maxPoolSize, 1000);
        
        return executor;
    }

    /**
     * AI API调用专用线程池
     * 用于并发调用AI API，提高响应速度
     */
    @Bean("aiApiExecutor")
    public Executor aiApiExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数：较大值，因为AI API调用是IO密集型
        int corePoolSize = Math.max(20, Runtime.getRuntime().availableProcessors() * 5);
        executor.setCorePoolSize(corePoolSize);
        
        // 最大线程数：更大值
        int maxPoolSize = Math.max(50, Runtime.getRuntime().availableProcessors() * 10);
        executor.setMaxPoolSize(maxPoolSize);
        
        // 队列容量
        executor.setQueueCapacity(500);
        
        // 线程空闲时间：30秒（AI调用可能较快完成）
        executor.setKeepAliveSeconds(30);
        
        // 线程名前缀
        executor.setThreadNamePrefix("AIApi-");
        
        // 拒绝策略：调用者运行策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(30);
        
        executor.initialize();
        
        log.info("[ReportPerformanceConfig][AI API线程池初始化完成] corePoolSize={}, maxPoolSize={}, queueCapacity={}",
                corePoolSize, maxPoolSize, 500);
        
        return executor;
    }
}
